package com.share.handler;


import com.share.common.result.ResponseResult;
import com.share.constant.SecurityConstant;
import com.share.domain.SecurityUser;
import com.share.user.admin.dtos.PayloadDTO;
import com.share.user.admin.vo.LoginVo;
import com.share.util.common.ResponseUtils;
import com.share.utils.TokenUtils;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 登陆成功返回信息
 */
@Component
public class CustomLoginAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    private final TokenUtils tokenUtils;

    public CustomLoginAuthenticationSuccessHandler(TokenUtils tokenUtils) {
        this.tokenUtils = tokenUtils;
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request,
                                        HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException {

        SecurityContextHolder.getContext().setAuthentication(authentication);

        SecurityUser securityUser = (SecurityUser) authentication.getPrincipal();

        List<SimpleGrantedAuthority> authorities = (List<SimpleGrantedAuthority>) securityUser.getAuthorities();

        Optional<List<SimpleGrantedAuthority>> optional = Optional.ofNullable(authorities);

        List<String> authList = optional.map(auth -> auth.stream()
                        .map(SimpleGrantedAuthority::toString)
                        .map(String::new)
                        .collect(Collectors.toList()))
                .orElseGet(ArrayList::new);

        PayloadDTO payloadDto = new PayloadDTO();
        payloadDto.setId(securityUser.getId());
        payloadDto.setUsername(securityUser.getUsername());
        payloadDto.setScope(securityUser.getRoles());
        payloadDto.setAuthorities(authList);
        payloadDto.setType(SecurityConstant.USER_TYPE_BACKSTAGE);

        String accessToken = tokenUtils.AccessToken(payloadDto);
        String refreshToken = tokenUtils.refreshToken(accessToken);
        LocalDateTime localDateTime = tokenUtils.getExp(accessToken);

        ResponseUtils.result(response,
                new ResponseResult<>(200, true, "登陆成功", Instant.now(),LoginVo
                        .builder()
                        .username(securityUser.getUsername())
                        .avatar(securityUser.getAvatar())
                        .nickname(securityUser.getNickname())
                        .username(securityUser.getUsername())
                        .roles(securityUser.getRoles())
                        .permission(authList)
                        .accessToken(accessToken)
                        .refreshToken(refreshToken)
                        .expires(localDateTime)
                        .build()
                )
        );
    }



}
